package cn.acewill.yxd.yunxundian.ui.sign;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.Api.SignApi;
import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.IsPointRemainAdapter;
import cn.acewill.yxd.yunxundian.adapter.mulityItemAdapter;
import cn.acewill.yxd.yunxundian.componet.CheckDataDialog;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.MailBean;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.SignUpInfo;
import cn.acewill.yxd.yunxundian.model.fbJson;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.r_trrAddtion;
import cn.acewill.yxd.yunxundian.model.reportHeadBean;
import cn.acewill.yxd.yunxundian.model.reportTailBean;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tReportHead;
import cn.acewill.yxd.yunxundian.model.tReportTail;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Main;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Row;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.RMainUtils;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

/**
 * Created by XXX on 2017/8/28.
 */

public class SendMailActivity extends BaseActivity implements View.OnClickListener,AdapterView.OnItemClickListener{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private TextView cman;
    private Button sendReceiver;
    private Button ccReceiver;
    private EditText mailContent,addReceiver;
    private mulityItemAdapter adapter;
    private int schid;
    private List<MailBean> mailList;
    private String diyiString,dierString;
    private List<String> selectList;
    private int whatreceiver = 0;
    private int xidongjihau=0;
    //加载推送人，如果无数据则不显示
    private LinearLayout hideArea;
    //推送人id
    private int Tomanid=0;
    private  ArrayList<Employee> emp;
    private ProgressDialog progressDialog;
    List<RMain.TablesBean.RowsBean.Q2Bean> allPointList;
    private List<fbJson> fbJsonList;
    private ArrayList<RMain> rMains;
    Gson gson=new Gson();
    private String url = "http://192.168.3.80/yxd/appservice/appservicehzm.aspx";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_mail);
        initView();
        CacheActivity.addActivity(this);
    }
    @Override
    protected void onResume() {
        super.onResume();
        MailListData();
        try {
                Schedule thisSch = db.selector(Schedule.class).where("ID", "=", schid).findFirst();
                if(thisSch!=null&&thisSch.getStates()<3) {
                    initRmain();
                    getSelectLostRR(thisSch);
                    getAllPointRR();
                    loadHeadTailData();
                    Log.e("head", tReportHeadList.size() + "");
                    Log.e("tail", tReportTailList.size() + "");
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    public void initRmain(){
        Schedule schedule = null;
        try {
            schedule = db.selector(Schedule.class).where("ID","=",schid).findFirst();
            sType type =db.selector(sType.class).where("ID","=",schedule.getSTypeID()).findFirst();
            rJson rjson = db.selector(rJson.class).where("ID","=",type.getReportId()).findFirst();
            if (rjson==null){
                showToast(this,"数据错误");
                finishActivity();
            }
            String rMainJson = rjson.getjSon();
            Type typeList = new TypeToken<ArrayList<RMain>>() {
            }.getType();
            rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(rMainJson), typeList);
        } catch (DbException e) {
            e.printStackTrace();

        }
    }

    private void initView(){
        schid=getIntent().getIntExtra("schId",0);
        Toolbar myToolBar = (Toolbar) findViewById(R.id.myToolBar);
        myToolBar.setTitle("");
        myToolBar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(myToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        myToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView title = (TextView) findViewById(R.id.titleName);
        title.setText("邮件发送");
//        cman= (TextView) findViewById(R.id.cman);
//        cman.setVisibility(View.GONE);
//
//        hideArea= (LinearLayout) findViewById(R.id.hideArea);
        //  mailTitle= (TextView) findViewById(R.id.mailTitle);
        mailContent= (EditText) findViewById(R.id.mailContent);
        addReceiver= (EditText) findViewById(R.id.addReceiver);
        sendReceiver = (Button) findViewById(R.id.sendReceiver);
        sendReceiver.setOnClickListener(this);
        ccReceiver = (Button) findViewById(R.id.ccReceiver);
        ccReceiver.setOnClickListener(this);
//        RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.myRadioGroup);
//        myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
//                switch (checkedId){
//                    case R.id.needPlan:
//                      final Dialog  myDialog=new Dialog(SendMailActivity.this);
//                        View view = LayoutInflater.from(SendMailActivity.this).inflate(R.layout.scoretype1_dialog, null);
//                        TextView listTitle = (TextView) view.findViewById(R.id.listTitle);
//                        listTitle.setText("推送人");
//                        ListView myScoreList = (ListView) view.findViewById(R.id.myList);
//                        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//                        myDialog.setContentView(view);
//                        //判断推送人数据是否为空
//                        if (emp!=null){
//                            simpleAdapter adapter=new simpleAdapter(SendMailActivity.this,emp);
//                            myScoreList.setAdapter(adapter);
//                            myScoreList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                                @Override
//                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                                    Employee employee= (Employee) parent.getItemAtPosition(position);
//                                    Tomanid=employee.getID();
//                                    cman.setText(employee.getFirstName());
//                                    cman.setVisibility(View.VISIBLE);
//
//                                    myDialog.dismiss();
//                                }
//                            });
//                        }
//                        myDialog.show();
//                        break;
//                    case R.id.cancelPlan:
//                        cman.setText("");
//                        cman.setVisibility(View.GONE);
//                        break;
//                }
//            }
//        });
        Button sendMail = (Button) findViewById(R.id.sendMail);
        sendMail.setOnClickListener(this);
        Button cancel_btn = (Button) findViewById(R.id.cancel_btn);
        cancel_btn.setOnClickListener(this);
        //getTuiSongRenData();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.sendReceiver:
                whatreceiver=1;
                if (TextUtils.isEmpty(diyiString)){
                    BaseActivity.showAnimaDialog(this,"无收件人可选");
                }else{
                    List<String> diyiList = new ArrayList<>();
                    String diyi[] = diyiString.split(",");
                    for (int i=0;i<diyi.length;i++){
                        String as[] = diyi[i].split(":");
                        if (!TextUtils.isEmpty(as[0])&&!TextUtils.isEmpty(as[1])){
                            //去掉分号
                            String mail = as[0].substring(1,as[0].length()-1);
                            String name = as[1].substring(1,as[1].length()-1);
                            diyiList.add(mail+":"+name);
                        }
                    }
                    creatDialog(diyiList);
                }

                break;
            case R.id.ccReceiver:
                whatreceiver=2;
                if (TextUtils.isEmpty(dierString)){
                    BaseActivity.showAnimaDialog(this,"无收件人可选");
                }else{
                    List<String> dierList = new ArrayList<>();
                    String dier[] = dierString.split(",");
                    for (int i=0;i<dier.length;i++){
                        String as[] = dier[i].split(":");
                        if (!TextUtils.isEmpty(as[0])&&!TextUtils.isEmpty(as[1])){
                            String mail = as[0].substring(1,as[0].length()-1);
                            String name = as[1].substring(1,as[1].length()-1);
                            dierList.add(mail+":"+name);
                        }
                    }
                    creatDialog(dierList);
                }
                break;
            case R.id.sendMail: {
                try {
                    Schedule thisSch = db.selector(Schedule.class).where("ID", "=", schid).findFirst();
                    if(thisSch!=null&&thisSch.getStates()<3)
                        submitTempRRData();
                    else
                        postMail();
                    break;
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            case R.id.cancel_btn:
                MaterialDialogUtils.showMaterialDialog(this, "是否放弃提交评估项", "确定", "取消", true, false, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        finish();
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    }
                });
                break;
        }
    }

    public void goToSelectTime(){
        MaterialDialogUtils.showMaterialDialog(this, "未设置行动计划开始时间！", "前往设置", "取消", false, true,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        startActivity(new Intent(SendMailActivity.this,MulitpleLostRRActivity.class).putExtra("schid",schid));
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        finish();
                    }
                });
    }

    public void MailListData(){
        Map<String,String> map = new HashMap<>();
        map.put("task","getMailAddressInfo");
        map.put("schid", schid+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String res[] = result.split("\\|");
                    if (res[0].equals("200")){
                        Gson gson  = new Gson();
                        Type typeList=new TypeToken<ArrayList<MailBean>>(){
                        }.getType();
                        mailList= gson.fromJson(pubClass.convertToArrayJson(result),typeList);
                        //只有一条数据
                        MailBean mail = mailList.get(0);
                        //拆分数据
                        if (mail.getDiyi().charAt(0)=='{'){
                          diyiString= mail.getDiyi().replace("{","").replace("}","").replace("","");
                        }
                        if (mail.getDier().charAt(0)=='{'){
                            dierString=mail.getDier().replace("{","").replace("}","");
                        }
                    }
                }
                @Override
                public void onFailture() {
                    BaseActivity.showAnimaDialog(SendMailActivity.this,"网络失去连接...");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void creatDialog(List<String> list){
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogview = inflater.inflate(R.layout.mulity_listview, null);
        ListView listview= (ListView) dialogview.findViewById(R.id.X_listview);
        adapter = new mulityItemAdapter(this,list);
        listview.setAdapter(adapter);
        selectList=new ArrayList<>();
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               adapter.setSecletion(position);
                adapter.notifyDataSetChanged();
               String str = (String) parent.getItemAtPosition(position);
                if (selectList.size()==0){
                    selectList.add(str);
                }else{
                    for (int i=0;i<selectList.size();i++){
                        if (selectList.get(i).equals(str)){
                            selectList.remove(i);
                            return;
                        }
                    }
                    selectList.add(str);
                }
            }
        });
        listview.setItemsCanFocus(true);
        listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("请选择收件人");
        builder.setView(dialogview);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (selectList.size()<=0){
                    return;
                }
                String str="";
                for (int i=0;i<selectList.size();i++){
                    String thstr[] = selectList.get(i).split(":");
                    str=str+thstr[0]+",";
                }
                str=str.substring(0,str.length()-1);
                if (whatreceiver==1){
                    sendReceiver.setText(str);
                }else{
                    ccReceiver.setText(str);
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (whatreceiver==2){ //ccreceiver
                    ccReceiver.setText("");
                }
            }
        });
        builder.create().show();
    }
    //上传数据
    public void postMail(){

        String Smail = sendReceiver.getText().toString().trim();
        if (TextUtils.isEmpty(Smail)){
            BaseActivity.showToast(this,"请选择收件人");
            return;
        }
        if(progressDialog==null)
        {
            progressDialog=new ProgressDialog(this);
            progressDialog.show();
        }

        if (progressDialog.isShowing()){
            progressDialog.setMessage("正在发送邮件");
        }
        String ccMail = ccReceiver.getText().toString().trim();
        String otherMail=addReceiver.getText().toString().trim();
        String content = mailContent.getText().toString().trim();
        Map<String,String> map = new HashMap<>();
        map.put("task","postMail");
        map.put("schid",schid+"");
     //   map.put("needtodo",xidongjihau+"");
       // map.put("toshopman",Tomanid+"");
        map.put("postmail","1");
        map.put("mailtoStr",Smail);
        map.put("mailBody",content);
      //  map.put("radio-choice-b",xidongjihau+"");
        map.put("toCCList",ccMail);
        map.put("addMail",otherMail);
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String str[] = result.split("\\|");
                    if (progressDialog.isShowing()){
                        progressDialog.dismiss();
                    }
                    if (str[0].equals("200")){
                        BaseActivity.showAnimaDialog(SendMailActivity.this,"邮件发送成功");
                        finishActivity();
                    }else{
                        BaseActivity.showAnimaDialog(SendMailActivity.this,"邮件发送失败");
                        finishActivity();
                    }
                }
                @Override
                public void onFailture() {
                    BaseActivity.showAnimaDialog(SendMailActivity.this,"邮件发送失败，请检查网络状态");
                   finishActivity();
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void finishActivity(){
        CacheActivity.finishActivity();
    }
    public void getTuiSongRenData(){
        final ProgressDialog pdialog=new ProgressDialog(this);
        pdialog.setMessage("加载中");
        pdialog.show();
        Map<String,String> map=new HashMap<>();
        map.put("task","getShopTodoEmpList");
        map.put("schid",schid+"");
        Log.e("schid",schid+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] array=result.split("\\|");
                    if(array[0].equals("200")){
                        //
                        Gson gson=new Gson();
                        Type typeList=new TypeToken<ArrayList<Employee>>(){}.getType();
                        emp=gson.fromJson(pubClass.convertToArrayJson(result),typeList);

                        //判断是否有数据，控制推送人显示或隐藏
                        if(emp!=null && emp.size()>0){
                            hideArea.setVisibility(View.VISIBLE);
                        }else{
                            hideArea.setVisibility(View.GONE);
                        }
                    }
                    if (pdialog.isShowing()){
                        pdialog.dismiss();
                    }
                }
                @Override
                public void onFailture() {
                    if (pdialog.isShowing()){
                        pdialog.dismiss();
                    }
                }
            },map);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*提交评估的数据，5s后执行postmail*/
    public void submitTempRRData(){

        if (allPointList!=null&&allPointList.size()>0){
            creatRowDialog(allPointList);
            return;
        }
//        String Smail = sendReceiver.getText().toString().trim();
//        if (TextUtils.isEmpty(Smail)){
//            BaseActivity.showAnimaDialog(this,"请选择收件人");
//            return;
//        }

        progressDialog=new ProgressDialog(this);
        progressDialog.setMessage("正在获取传失分项数据");
        //防止progressbar被关闭
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode==KeyEvent.KEYCODE_BACK){
                    return true;
                }else{
                    return false;
                }
            }
        });
        progressDialog.show();
        List<tempLostRR> temp = null;
        List<r_trrAddtion> trraList = null;
        try {
            //拿到上传的数据
            temp = db.selector(tempLostRR.class).where("schId", "=", schid).findAll();
            trraList = db.selector(r_trrAddtion.class).where("schid","=",schid).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        final String currentTime = sdf.format(date);
        final String currentTimeT = currentTime.replace(' ', 'T');
        try {
            Schedule thisSch = db.selector(Schedule.class).where("ID", "=", schid).findFirst();
//            if (!TextUtils.isEmpty(cman.getText().toString().trim())) {
//                xidongjihau = 1;
//            } else {
//                xidongjihau = 0;
//            }
            Map<String, Object> map = new HashMap<>();
            Gson gson = new Gson();
            //提交失分项
            map.put("task", "postall");
            map.put("schid", schid);
            if (thisSch.getRealStartTime() != null)
                map.put("schstarttime", thisSch.getRealStartTime().replace("T", " "));
            else
                map.put("schstarttime", currentTime);
            if (temp!=null){
                map.put("tIrrList", gson.toJson(temp));
                Log.e("rtlist",gson.toJson(temp));
            }

            if(trraList!=null) {
                Gson gsonTrra = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                map.put("trrAddtionData", gsonTrra.toJson(trraList));
            }
            //行动计划提交
            if (fbJsonList!=null&&fbJsonList.size()>0){
                map.put("fbJson",gson.toJson(fbJsonList));
                Log.e("fbjosn",gson.toJson(fbJsonList));
                xidongjihau=1;
            }
            //行动计划时间
            if (xingdongTime!=null && !TextUtils.isEmpty(xingdongTime)){
                Log.e("extime",xingdongTime);
                map.put("extime",xingdongTime);
            }
            map.put("needtodo", xidongjihau);
           // map.put("toshopman", Tomanid);
            if (tReportHeadList!=null && tReportHeadList.size()>0){
                map.put("tReportHead",gson.toJson(tReportHeadList));

            }if (tReportTailList!=null && tReportTailList.size()>0){
               map.put("tReportTail", gson.toJson(tReportTailList));
            }

            //图片
            int count = 0;
            if (temp != null && temp.size() > 0) {
                for (tempLostRR rr : temp) {
                    String photo = rr.getJpgStr();
                    String video = rr.getVideoStr();
                    //去掉最后一个逗号,
                    if (!TextUtils.isEmpty(photo)) {
                        String[] ss = photo.substring(0, photo.length() - 1).split(",");
                        //判断文件是否存在
                        for (int i = 0; i < ss.length; i++) {
                            File file = new File(ss[i]);
                            if (file.exists()) {
                                map.put("uploadfile" + count, file);
                                count++;
                            }
                        }
                    }
                    if (!TextUtils.isEmpty(video)) {
                        String[] sp = video.substring(0, video.length() - 1).split(",");

                        for (int k = 0; k < sp.length; k++) {
                            File file = new File(sp[k]);
                            if (file.exists()) {
                                map.put("uploadfile" + count, file);
                                count++;
                            }
                        }
                    }
                }
            }
            //打包签名
            CommonMapBean cmb = db.selector(CommonMapBean.class).where("CmType", "=", "门店签名")
                    .and("IndexNum", "=", schid + "")
                    .findFirst();
            if (cmb != null) {
                if (!cmb.getCmValue().toString().equals("")) {
                    File f = new File(cmb.getCmValue().toString());
                    map.put("signjpg", f);
                }
            }
            progressDialog.setMessage("正在上传失分项数据");
        //    String url="http://192.168.2.102/yxd/appservice/appServiceHzm.aspx";
            pubClass.UpLoadFile(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String[] resArry = result.split("\\|");
                    if (resArry[0].equals("200")) {
                        Toast.makeText(SendMailActivity.this, "数据上传成功", Toast.LENGTH_SHORT).show();
                        CommonMapBean cmb = new CommonMapBean();
                        cmb.setCmType("fenshu");
                        cmb.setServerId(schid);
                        cmb.setCmValue(resArry[3]);
                        try {
                            db.saveOrUpdate(cmb);
                            Schedule schedule = db.selector(Schedule.class).where("ID", "=", schid + "").findFirst();
                            schedule.setStates(3);
                            schedule.setRealEndTime(currentTimeT);
                            db.saveOrUpdate(schedule);
                            //删除本地的templostrr及文件
                            tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schid).findFirst();
//                            if (!TextUtils.isEmpty(rr.getJpgStr())){
//                                String[] ss = rr.getJpgStr().substring(0, rr.getJpgStr().length() - 1).split(",");
//                                //判断文件是否存在
//                                for (int i = 0; i < ss.length; i++) {
//                                    File file = new File(ss[i]);
//                                    if (file.exists()) {
//                                        file.delete();
//                                    }
//                                }
//                            }
//                            if (!TextUtils.isEmpty(rr.getVideoStr())){
//                                String[] sv = rr.getVideoStr().substring(0, rr.getVideoStr().length() - 1).split(",");
//                                for (int k=0;k<sv.length;k++){
//                                    File vidoefile=new File(sv[k]);
//                                    if (vidoefile.exists()){
//                                        vidoefile.delete();
//                                    }
//                                }
//                            }
                            //可能出现没数据提交
                            if (rr!=null){
                                db.deleteById(tempLostRR.class,rr.get_ID());
                                Log.e("aaaa","删除成功");
                            }
                            if(!resArry[1].equals("noMsg")) {
                                Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                                Type tfmType = new TypeToken<ArrayList<t_Feedback_Main>>() {
                                }.getType();
                                Type tfrType = new TypeToken<ArrayList<t_Feedback_Row>>() {
                                }.getType();
                                ArrayList<t_Feedback_Main> tfmList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[2]), tfmType);
                                ArrayList<t_Feedback_Row> tfrList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[1]), tfrType);
                                for (t_Feedback_Main tfm : tfmList) {
                                    t_Feedback_Main tfmQuery = db.selector(t_Feedback_Main.class).where("Id", "=", tfm.getId()).findFirst();
                                    if (tfmQuery != null) {
                                        tfm.set_ID(tfmQuery.get_ID());
                                    }
                                    db.saveOrUpdate(tfm);
                                    //Log.i("xutilsDB", tfm.toString());
                                }
                                for (t_Feedback_Row tfr : tfrList) {
                                    t_Feedback_Row tfrQuery = db.selector(t_Feedback_Row.class).where("Id", "=", tfr.getId()).findFirst();
                                    if (tfrQuery != null) {
                                        tfr.set_ID(tfrQuery.get_ID());
                                    }
                                    db.saveOrUpdate(tfr);
                                    //Log.i("xutilsDB", tfr.toString());
                                }
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        progressDialog.setMessage("失分项数据上传成功，请等待准备发送邮件");
                        completetUpLoad();
//                    } else if (resArry[0].equals("201")) {
//                       if (progressDialog.isShowing()){
//                           progressDialog.dismiss();
//                           BaseActivity.showAnimaDialog(SendMailActivity.this,"失分项数据上传失败");
//                       }
                    } else if (resArry[0].equals("210")) {
                        if (progressDialog.isShowing()){
                            progressDialog.dismiss();
                            BaseActivity.showAnimaDialog(SendMailActivity.this,"任务已提交");
                        }
                    }else{

                        if (progressDialog.isShowing()){
                            progressDialog.dismiss();
                            BaseActivity.showAnimaDialog(SendMailActivity.this,"失分项数据上传失败");
                        }
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    if (progressDialog.isShowing()){
                        progressDialog.dismiss();
                        BaseActivity.showAnimaDialog(SendMailActivity.this,"连接超时请检查网络状况");
                    }
                }
            });

        } catch(DbException e){
            e.printStackTrace();
        }
    }

    public void completetUpLoad(){
        //判断是否需要发送邮件，5s后发送邮件
        String Smail = sendReceiver.getText().toString().trim();
        //提交完后签出门店
        try {
            SignUpInfo sui = db.selector(SignUpInfo.class).where("_ID", "=", MainActivity.signId + "").findFirst();
            if (sui!=null){
                Log.e("signOut","签出");
                sui.setOutTime(BaseActivity.getNowDate());
                db.saveOrUpdate(sui);
                MainActivity.signId = 0;
                SignApi.getInstance().SignOutByNet(sui);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(Smail)){
            finishActivity();
        }else{
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //SubmitReport.this.finish();
                    postMail();

                }
            }, 5000);
        }
    }
    int reportMainid;
    List<tReportHead> tReportHeadList=new ArrayList<>();
    List<tReportTail> tReportTailList=new ArrayList<>();
    public void loadHeadTailData() throws DbException {

        if (rMains!=null&&rMains.size()>0){
            RMain.TablesBean tablesBean=rMains.get(0).getTables().get(0);
            reportMainid= tablesBean.getQ1().getReportMainID();
        }
      List<reportHeadBean>  mheadList= db.selector(reportHeadBean.class).where("reportMainID","=",reportMainid).orderBy("orderValue").findAll();
      List<reportTailBean>  mtailList=db.selector(reportTailBean.class).where("reportMainId","=",reportMainid).orderBy("orderValue").findAll();

        if (mheadList!=null && mheadList.size()>0){
            for (reportHeadBean rh:mheadList){
             tReportHead trh= db.selector(tReportHead.class).where("reportHeadId","=",rh.getID()).and("ID","=", schid).findFirst();
                if (trh!=null){
                    tReportHeadList.add(trh);
                    Log.e("tre",tReportHeadList.size()+"");
                }
            }
        }
        Log.e("test", "loadHeadTailData: "+gson.toJson(tReportHeadList) );
        if (mtailList!=null && mtailList.size()>0){
                for (reportTailBean rt:mtailList){
                    tReportTail trt=db.selector(tReportTail.class).where("reportTailId","=",rt.getID()).and("ID","=", schid).findFirst();
                    if (trt!=null){
                        tReportTailList.add(trt);
                        Log.e("trt",tReportTailList.size()+"");
                    }
                }
            }
    }
    //获取当前schid的所有的point>=1的数据

    public void getAllPointRR() throws DbException {
         allPointList = new ArrayList<>();
        //循环取出所有的isponit>=1的数据
        List<RMain.TablesBean> tables= rMains.get(0).getTables();
        for (RMain.TablesBean table:tables){
            List<RMain.TablesBean.RowsBean> rowsBeen=table.getRows();
            for (RMain.TablesBean.RowsBean rows:rowsBeen){
                // TODO: 2017/9/5 记得修改条件
                if (rows.getQ2().getIsPoint()>=2){
                    allPointList.add(rows.getQ2());
                }
            }
        }
        Log.e("Listall1",allPointList.size()+"");
        //移出已填必填项
        List<tempLostRR> rr=db.selector(tempLostRR.class).where("schId","=",schid).findAll();
        //是否存在必填项
        if (allPointList!=null&&allPointList.size()>0){
            if (rr==null||rr.size()==0){
                creatRowDialog(allPointList);
            }else{
                for (tempLostRR r:rr){
                    for (int k=0;k<allPointList.size();k++){
                        if (allPointList.get(k).getID()==r.getRRowId()){
                            allPointList.remove(k);
                        }
                    }
                }
                if (allPointList.size()==0){
        //            BaseActivity.showAnimaDialog(this,"必填评估项已评估");
                }else{
                    creatRowDialog(allPointList);
                }
            }
        }
    }

    //获取templostRR的行动计划
    private String xingdongTime = "";
    private void  getSelectLostRR(Schedule sch) throws DbException {
       List<tempLostRR> temp = db.selector(tempLostRR.class).where("schId", "=", schid).findAll();
        sType type =db.selector(sType.class).where("ID","=",sch.getSTypeID()).findFirst();
        List<tempLostRR> xingdongRR = new ArrayList<>();
        if (temp!=null){
           List<tempLostRR> nRr = CheckDataDialog.getInstance(this).excludeSameRR(temp,rMains);
           if (nRr!=null){
               for (int i=0;i<temp.size();i++){
                   tempLostRR rr = temp.get(i);
                   if (rr.isFbIsCheck()){
                       xingdongRR.add(rr);
                       xingdongTime = rr.getXiongdongTime();
                   }
               }
           }
           //数据迁移
           if (xingdongRR.size()>0){
               fbJsonList = new ArrayList<>();
               for (tempLostRR rr:xingdongRR){
                   fbJson fjson = new fbJson(rr.getRRowId(),rr.getSchId(),rr.getXindongId());
                   fbJsonList.add(fjson);
               }
             //  showAnimaDialog(this,fbJsonList.size()+"个");
           }
       }
       //判断是否需要去设置任务时间,并且不是自定义任务
       if (fbJsonList!=null&&fbJsonList.size()>0&&type.getReportId()!=1){
           for (tempLostRR fb:xingdongRR){
               if (fb.isFbIsCheck()){
                   if(xingdongTime==null||TextUtils.isEmpty(xingdongTime)){
                       goToSelectTime();
                       break;
                   }
               }
           }
       }
    }


    private Dialog mydialog;
    public void creatRowDialog(List<RMain.TablesBean.RowsBean.Q2Bean> list){
        mydialog=new Dialog(this);
        mydialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(this).inflate(R.layout.ispoint_remail_listview, (ViewGroup) getWindow().getDecorView(),false);
        final ListView dialoglist= (ListView) view.findViewById(R.id.isPointListView);
        Button cancel_btn= (Button) view.findViewById(R.id.cancel_btn);
        cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mydialog.isShowing()){
                    mydialog.dismiss();
                }
                finish();
            }
        });
        dialoglist.setOnItemClickListener(this);
        IsPointRemainAdapter pointadapter=new IsPointRemainAdapter(this,list);
        dialoglist.setAdapter(pointadapter);
        mydialog.setContentView(view);
        mydialog.setCancelable(true);
//        mydialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
//            @Override
//            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                if (keyCode==KeyEvent.KEYCODE_BACK){
//                    return true;
//                }else{
//                    return false;
//                }
//            }
//        });
       // mydialog.create();
        mydialog.show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        RMain.TablesBean.RowsBean.Q2Bean bean = (RMain.TablesBean.RowsBean.Q2Bean) parent.getItemAtPosition(position);
        if (mydialog.isShowing()){
            mydialog.dismiss();
        }
        Intent in=new Intent(this,MarkPhotoActivity.class);
        in.putExtra("title",bean.getReportRowName());
        in.putExtra("sName",bean.getSName());
        in.putExtra("type",bean.getItemType());
        in.putExtra("maxScore",bean.getMaxScore());
        in.putExtra("id",bean.getID());
        in.putExtra("tag",1);
        in.putExtra("schid",schid);
        in.putExtra("ispoint",2);
        startActivityForResult(in,101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 101:
                try {
                    getAllPointRR();
                } catch (DbException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
